<template>
  <div class="">
    <div class="mask" @click="close()"></div>
    <div class="paymodal codemodal" v-if="payStep === 1">
      <div class="modal_head">
        <span class="fl">收银台</span>
        <a href="javascript:" @click="close()" class="close iconfont">关闭</a>
      </div>
      <div class="modal_body">
        <div class="tip" v-if="order.payType === 1">支付宝支付 {{this.order.shouldPay}}元</div>
        <div class="tip" v-else>微信支付 {{this.order.shouldPay}}元</div>
        <div class="code" id="qrcode">
          <canvas id="canvas222"></canvas>
        </div>
        <p class="tip2" v-if="order.payType === 2">请使用支付宝扫描二维码支付以完成订单</p>
        <p class="tip2" v-else>请使用微信扫描二维码支付以完成订单</p>
        <div class="finish_pay" @click="getOrderInfoSelf">完成支付如果页面没有跳转请点击此处</div>
        <div class="tip_panel">
          提示: <br>
          支付成功前请不要手动关闭页面<br>
          二维码两个小时内有效,请及时扫码支付，否则订单将被取消
        </div>
      </div>
    </div>
    <div class="paymodal" v-else-if="payStep === 0">
      <div class="modal_head">
        <span class="fl">收银台</span>
        <a href="javascript:" @click="close()" class="close iconfont">关闭</a>
      </div>
      <div class="modal_body" v-if="courseData">
        <table class="table">
          <tr>
            <th>课程名称</th>
            <th>课程价格</th>
          </tr>
          <tr>
            <td width="300">
              <div class="" style="width:320px;">
                <div class="img" v-if="courseData.courseLogo"><img :src="courseData.courseLogo" alt=""></div>
                <div class="name">{{courseData.courseName}}</div>
              </div>
            </td>
            <td style="font-size: 16px;text-align: center" v-if="!courseData.isFree">
                  <span v-if="courseData.courseOriginal == courseData.courseDiscount">¥{{courseData.courseOriginal | toFixed2}}元{{courseData.costTimeType | costTimeTypeChange}}</span>
                  <span v-if="courseData.courseOriginal != courseData.courseDiscount">
                    <span style="text-decoration: line-through;">原价¥{{courseData.courseOriginal | toFixed2}}元{{courseData.costTimeType | costTimeTypeChange}}</span>
                    <span style="color: red">现价¥{{courseData.courseDiscount | toFixed2}}元{{courseData.costTimeType | costTimeTypeChange}}</span>
                  </span>
            </td>
            <td style="font-size: 16px;text-align: center" v-if="courseData.isFree">
              ¥0元
            </td>
          </tr>
        </table>
        <div v-if="this.studyCardSize!=0" style="text-align: center;background-color: lightsteelblue;padding-bottom:5px">
          <hr>
          <span style="font-size: 16px;font-weight: bold">学习卡({{this.studyCardSize}}张)</span><br/>
        </div>
        <div v-if="this.studyCardSize!=0" class="study_card_type" >
          <div v-for="(item, index) in studyCardList">
            <input type="radio" :id="item.id" name="studyCardCouponType" :value="item.id" @click="selectStudyCard(item,1)">
            <label :for="item.id" class="study_card_detail">
              <span style="color: white">
                  {{item.cardTitle | cutTile}}<br/>
                  剩余面额：{{(item.totalFaceValueAmount-item.usedFaceValueAmount-item.frozenFaceValueAmount) | toFixed2}}元<br/>
                  [有效期:{{item.studyCardTimeBegin}}至{{item.studyCardTimeEnd}}]
                </span>
              <span v-if="item.id==selectedId" style="position: relative;float:right;border:1px solid blue;background-color: blue;color: white;">已选择√</span>
            </label>
          </div>
        </div>
        <div v-if="this.couponSize!=0" style="text-align: center;background-color: lightsteelblue;padding-bottom:5px">
          <hr>
          <span style="font-size: 16px;font-weight: bold">优惠券({{this.couponSize}}张)</span><br/>
        </div>
        <div v-if="this.couponSize!=0" class="coupon_type">
          <div v-for="(item, index) in couponList">
            <input type="radio" :id="item.id" name="studyCardCouponType" :value="item.id" @click="selectCoupon(item,2)">
            <label :for="item.id" class="coupon_detail">
              <span style="color: white">
                  {{item.couponName | cutTile}}<br/>
                  优惠金额:<span style="font-weight: bold;color: red">{{item.couponAmount}}元</span><span v-if="item.isLimitCourse==0">[不限制课程]</span><span v-if="item.isLimitCourse==1">[部分课程适用]</span><br/>
                  [有效期:{{item.couponTimeBegin}}至{{item.couponTimeEnd}}]
               </span>
              <span v-if="item.id==selectedId" style="position: relative;float:right;border:1px solid blue;background-color: blue;color: white;">已选择√</span>
            </label>
          </div>
        </div>
        <div class="should_pay">
          <span style="float: left; margin-left: 400px;font-size: 16px">需支付<span style="font-size:20px;font-weight: bold;color: #e01c2b">{{this.order.shouldPay}}</span>元</span>
        </div>
        <div class="pay_type">
          <input type="radio" id="payType2" name="payType" value="1" v-if="isOpenZfbPc==1" @click="setPayType(1)">
          <label for="payType2" v-if="isOpenZfbPc==1" class="pay pay_ali"></label>
          <input type="radio" id="payType1" name="payType" value="2" v-if="isOpenWeixinpayPc==1" @click="setPayType(2)">
          <label for="payType1" v-if="isOpenWeixinpayPc==1" class="pay pay_weixin"></label>
        </div>
        <div class="remark">
          <label>备注:</label>
          <input type="text" v-model="order.remark" placeholder="请输入你的备注!">
        </div>
        <div class="modal_foot">
          <button class="solid_btn" @click="submitOrderWarn" :disabled="btntext === '正在提交...'">{{btntext}}</button>
        </div>
      </div>
    </div>
    <div class="paymodal payrun" v-else-if="payStep === 2">
      <div class="modal_head">
        <span class="fl">收银台</span>
        <a href="javascript:" @click="close()" class="close iconfont">关闭</a>
      </div>
      <div class="modal_body">
        <div class="icon iconfont c_green minIcon">&#xe69f;<span class="c_333 font_14">订单支付成功!</span></div>
        <!-- <div class="tip">支付成功</div> -->
        <div class="center border_b">
          <a class="solid_btn order_btn" v-if="courseData.courseSubject == 1" :href="'/view/'+courseData.id">立即学习</a>
          <a class="solid_btn order_btn" v-else-if="courseData.courseSubject == 2" :href="'/live/detail/'+courseData.id">立即学习</a>
          <a class="solid_btn order_btn" v-else-if="courseData.courseSubject == 3" :href="'/live/bunch/'+courseData.id">立即学习</a>
          <a class="solid_btn order_btn" v-else href="javascript:" @click="reload">确定</a>
          <a class="solid_btn order_btn" target="_blank" href="/account/order">查看订单</a>
        </div>
        <div class="ewm_img" v-if="webInfo && webInfo.weixinXiaochengxuQrUrl">
          <img :src="webInfo.weixinXiaochengxuQrUrl" alt="">
          <p class="mgt10">微信扫码关注小程序</p>
          <p>学习更便捷</p>
        </div>
      </div>
    </div>
    <div class="paymodal payrun" v-else-if="payStep === 3">
      <div class="modal_head">
        <span class="fl">收银台</span>
        <a href="javascript:" @click="close()" class="close iconfont">关闭</a>
      </div>
      <div class="modal_body">
        <div class="icon iconfont c_red">&#xe68c;</div>
        <div class="tip">支付失败</div>
        <div class="center">
          <button class="solid_btn" @click="{payStep = 0}">重新购买</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import {orderMainSave, orderInfo,checkPayResult} from '~/api/order.js'
  import {studyCardList,couponUserList,systemConfig} from '~/api/account/user.js'
  import QRCode from 'qrcode'
  import VueCookie from 'vue-cookie'

  export default {
    props: {
      data: {
        type: [Object, Array],
        default: null
      },
      no: {
        type: String,
        default: ''
      },
      isCourse: {
        type: Boolean
      }
    },
    data () {
      return {
        studyCardList: [],
        couponList: [],
          studyCardSize: '',
          couponSize: '',
        isVip: false,
        btntext: '下一步',
        checkPay: false,
        userInfo: JSON.parse(VueCookie.get("wangxinUserInfo")),
        courseData: '',
        order: {
          courseId: 0,
          payType: 0,
          shouldPay: 0,
          remark: '',
          cardId: '',//如果cardType是学习卡，就是学习卡ID，如果cardType是优惠券，就是优惠券ID
          cardType: '',//选择学习卡为1，选择优惠券为2
          orderNo: ''
        },
        orderInfo: {
            payType: 1
        },
        payStep: 0,
        player: null,
        selectedId: '',
          isOpenZfbPc: 0,
          isOpenWeixinpayPc: 0
      }
    },
      filters: {
          cutTile(value) {
              if (!value) return ''
              if (value.length > 14) {
                  return value.slice(0, 14) + '...'
              }
              return value
          },
          costTimeTypeChange(value){
              //计费类型，0代表长期，1按天，2按周(7天)，3按月(30天)，4按年(365天)
              if(value===0){
                  return "";
              }else if(value===1){
                  return "/天";
              }else if(value===2){
                  return "/周";
              }else if(value===3){
                  return "/月";
              }else if(value===4){
                  return "/年";
              }else{
                  return "";
              }
          },
          toFixed2(value){
              if(typeof(value)=='undefined'){
                  return '数据错误，请重新尝试';
              }
              return Number(value.toFixed(2));
          }
      },

    mounted () {
      // this.qrcode('weixin://wxpay/bizpayurl?pr=GlkCzqF');
      console.log(this.$router)
      this.order.courseId = this.data.course.id;
      this.courseData = this.data.course;
      console.log(this.courseData)
      this.getStudyCardList();
      this.getCouponUserList();
      this.getSystemConfig();

      this.order.shouldPay = this.toFixed22(this.courseData.courseDiscount);
    },
    methods: {
        toFixed22(value){
            if(typeof(value)=='undefined'){
                this.$msgBox({
                    content: '请等待页面数据加载完整再点击购买按钮',
                    isShowCancelBtn: false
                }).then(() => {

                }).catch(() => {
                })
                return;
            }
             return Number(value.toFixed(2));
        },
        setPayType(payType){
            this.order.payType = payType;
        },
        selectStudyCard(item,cardType){

           if(item.id==this.selectedId){
               this.selectedId = '';
               this.order.cardId = '';
               this.order.cardType = 0;
               this.order.shouldPay = this.courseData.courseDiscount.toFixed(2);
               return;
           }
            console.log("item.totalFaceValueAmount:"+item.totalFaceValueAmount);
            console.log("item.usedFaceValueAmount:"+item.usedFaceValueAmount);
            console.log("item.frozenFaceValueAmount:"+item.frozenFaceValueAmount);

            let canUseValueAmount = item.totalFaceValueAmount-item.usedFaceValueAmount-item.frozenFaceValueAmount;
           if(canUseValueAmount>0){
               if(canUseValueAmount>=this.courseData.courseDiscount.toFixed(2)){
                   this.order.shouldPay = 0;
               }else{
                   this.order.shouldPay = this.courseData.courseDiscount.toFixed(2)-canUseValueAmount.toFixed(2);
               }
           }
            this.order.shouldPay = this.order.shouldPay.toFixed(2);
           this.selectedId = item.id;

           this.order.cardType = cardType;
           this.order.cardId = item.id;
        },
       selectCoupon(item,cardType){
           if(item.id==this.selectedId){
               this.selectedId = '';
               this.order.cardId = '';
               this.order.cardType = 0;
               this.order.shouldPay = this.courseData.courseDiscount.toFixed(2);
               return;
           }
            let couponAmount = item.couponAmount;
            if(couponAmount>0){
                if(couponAmount>=this.courseData.courseDiscount.toFixed(2)){
                    this.order.shouldPay = 0;
                }else{
                    this.order.shouldPay = this.courseData.courseDiscount.toFixed(2)-couponAmount;
                }
            }
           this.order.shouldPay = this.order.shouldPay.toFixed(2);
            this.selectedId = item.id;

           this.order.cardType = cardType;
           //this.order.cardId = this.selectedId;
           this.order.cardId = item.couponId;

       },
        //是否过期
        isOutDate(endDate){
            let endDateTime = new Date(endDate).getTime();
            let nowTime = new Date().getTime();
            if(nowTime>endDateTime){
                return true;
            }else{
                return false;
            }
        },
        getCouponUserList () {
            couponUserList({
            'courseId':this.data.course.id
            }).then(res => {
                res = res.data;
                if (res.code === 200) {
                    this.couponList = res.data.list || [];
                    this.couponSize = this.couponList.length;
                } else {
                    if (res.code >= 300 && res.code < 400) {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).then(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', res.code)
                        }).catch(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', res.code)
                        })
                    } else {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).catch(() => {})
                    }
                }
            }).catch(() => {
            })
        },
        getSystemConfig () {
            systemConfig({

            }).then(res => {
                res = res.data;
                if (res.code === 200) {
                   // console.log("====>"+res.data)
                    this.isOpenZfbPc = res.data.isOpenZfbPc;
                    this.isOpenWeixinpayPc = res.data.isOpenWeixinpayPc;
                } else {
                    if (res.code >= 300 && res.code < 400) {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).then(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', result.code)
                        }).catch(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', result.code)
                        })
                    } else {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).catch(() => {})
                    }
                }
            }).catch(() => {
            })
        },
        getStudyCardList () {
            studyCardList({
                'courseId':this.data.course.id
            }).then(res => {
                res = res.data;
                if (res.code === 200) {
                    this.studyCardList = res.data.list || [];
                    this.studyCardSize = this.studyCardList.length;
                } else {
                    if (res.code >= 300 && res.code < 400) {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).then(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', result.code)
                        }).catch(() => {
                            this.$store.dispatch('REDIRECT_LOGIN', result.code)
                        })
                    } else {
                        this.$msgBox({
                            content: res.msg,
                            isShowCancelBtn: false
                        }).catch(() => {})
                    }
                }
            }).catch(() => {
            })
        },
      reload () {
        window.location.reload();
      },
      close (event) {
        this.checkPay = true;
        this.$emit('hidefun', event);
      },
      sel (cno) {
        this.checkPay = true;
        this.$emit('btnClick', cno)
      },
      qrcode2 (url) {
        console.log("ddd-------");
        let canvas222 = document.getElementById('canvas222');
        QRCode.toCanvas(canvas222, url, {
          width: 180,
          height: 180
        }, function (error) {
            if (error) {
              console.error(error);
            }else {
              console.log('success!')
            }
        })
      },
      startView () {

      },
        submitOrderWarn(){
            console.log("支付类型："+this.orderInfo.payType);
            this.$msgBox({
                content: "确定提交订单吗？",
                isShowCancelBtn: true
            }).then(() => {
                this.submit();
            }).catch(() => {})
        },
      submit () {
          let that = this;
          console.log("订单内容："+JSON.stringify(this.order));
          if(parseFloat(that.order.shouldPay) > 0){
              if(that.order.payType === 0){
                  this.$msgBox({
                      content: '必须选择支付方式',
                      isShowCancelBtn: false
                  })
                  return;
              }
          }

          this.payStep = 1;
       // if(1===1) {
       //     setTimeout(function () {
        //        that.qrcode2('66777');
         //   }, 1000);
         //   return;
       // }
        that.btntext = '正在提交...';
          orderMainSave(that.order).then(res => {
          res = res.data;
          console.log(res)
          that.btntext = '下一步';
          if (res.code === 200) {
            that.payStep = 1;
            that.orderInfo = res.data;
            setTimeout(function () {
              that.qrcode2(res.data.qrCode);
            }, 200);
            this.order.orderNo = res.data.orderNo;
            that.getOrderInfo(res.data.orderNo)
          } else if (res.code >= 300 && res.code < 400) {
            this.$msgBox({
              content: res.msg,
              isShowCancelBtn: false
            }).then(() => {
              this.$store.dispatch('REDIRECT_LOGIN');
            }).catch(() => {})
          } else {
            this.$msgBox({
              content: res.msg,
              isShowCancelBtn: false
            }).catch(() => {})
          }
        }).catch(() => {
          this.$msgBox({
            content: '提交失败,请重试',
            isShowCancelBtn: false
          })
          that.btntext = '重新提交';
        })
      },
      getOrderInfo (no) {
        let that = this;
        if (this.checkPay) {
          return false;
        }
          checkPayResult({orderNo: no}).then(res => {
          res = res.data
          console.log(res)
          if (res.data.payStatus === 0) {
            setTimeout(function () {
              that.getOrderInfo(no);
            }, 2000);
          } else if (res.data.payStatus === 1) {
              this.close();
              this.$msgBox({
                content: '购买成功',
                isShowCancelBtn: false
              }).then(res => {
                window.location.reload();
              }).catch(() => {
                window.location.reload();
              })
            } else {
              that.payStep = 2;
            }
        })
      },
        getOrderInfoSelf () {//手动点击完成支付
            let that = this;

            if (this.checkPay) {
                return false;
            }
            checkPayResult({orderNo: that.order.orderNo}).then(res => {
                res = res.data
                console.log(res)
                if (res.data.payStatus === 0) {
                    this.$msgBox({
                        content: '尚未完成支付',
                        isShowCancelBtn: false
                    }).then(res => {
                    }).catch(() => {
                    })
                    return;
                } else if (res.data.payStatus === 1) {
                    this.close();
                    this.$msgBox({
                        content: '购买成功',
                        isShowCancelBtn: false
                    }).then(res => {
                        window.location.reload();
                    }).catch(() => {
                        window.location.reload();
                    })
                } else {
                    that.payStep = 2;
                }
            })
        }
    }
  }
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.payrun{
  min-height: 180px;
  .modal_body{
    padding: 30px;
    //height: 180px;
  }
  .ewm_img {
    width: 130px;
    display: block;
    margin: 10px auto 0;
    text-align: center;
    img {
      width: 130px;
      height: 130px;
    }
    p {
      line-height: 20px;
    }
  }
  .icon{
    font-size: 80px;
    width: 80px;
    margin: 0 auto;
    text-align: center;
    &.minIcon {
      font-size: 26px;
      width: 160px;
      span {
        position: relative;
        top: -5px;
        padding-left: 6px;
      }
    }
  }
  .order_btn {
    background: #fff;
    border: 1px solid rgb(180, 180, 180);
    color: #999;
    text-decoration: none;
    margin: 30px 5px;
  }
  .tip{
    font-size: 16px;
    text-align: center;
    padding-bottom: 20px;
  }
  .c_green{
    color: #05d005;
  }
}
.codemodal{
  .tip{
    margin: 30px auto 0;
    text-align: center;
    font-size: 16px;
  }
  .code{
    width: 182px;
    height: 182px;
    border: 1px solid #ddd;
    margin: 20px auto;
  }
  .tip2{
    margin: 0 auto;
    width: 380px;
    padding: 13px 0 13px 70px;
    height: 40px;
    line-height: 20px;
    font-size: 14px;
    color: black;
    background-color: lightskyblue;
  }
  .finish_pay{
    margin: 10px auto;
    width: 380px;
    height: 20px;
    line-height: 20px;
    font-size: 14px;
    color: black;
    text-align: center;
    cursor:pointer;
    text-decoration:underline;
    background-color: greenyellow;
  }
  .tip_panel{
    margin-top: 20px;
    padding: 20px;
    line-height: 20px;
    border-top: 1px solid #f1f1f1;
  }
}
.paymodal{
  position: fixed;
  left: 50%;
  top: 10%;
  z-index: 999;
  width: 720px;
  margin-left: -240px;
  background-color: #fff;
  border-radius: 0px;
  height: 500px;
  overflow: scroll;
  .modal_head{
    line-height: 46px;
    background-color: #f9f9f9;
    text-align: right;
    padding: 0 20px;
    .close{
      font-size: 14px;
    }
  }
  .modal_foot{
    border-top: 1px solid #e7e7eb;
    padding: 20px;
    text-align: center;
  }
  .table{
    width: 100%;
  }
  th{
    line-height: 36px;
    background-color: #f8f8f8;
  }
  td{
    vertical-align: middle;
    padding: 20px;
  }
  .name{
    width: 140px;
    padding-left: 12px;
    font-size: 16px;
  }
  .img{
    display: inline-block;
    width: 120px;
    padding: 0;
  }
  .name{
    display: inline-block;
    vertical-align: top;
  }
  .tabs {
    height: 48px;
    .tab{
      float: left;
      line-height: 46px;
      text-align: center;
      font-size: 16px;
      width: 50%;
    }
    span{
      cursor: default;
      display: inline-block;
      line-height: 46px;
    }
    .on{
      color: #ee7e00;
      span{
        border-bottom: 2px solid #ee7e00;
      }
    }
  }
  .remark{
    padding: 20px;
    overflow: hidden;
    font-size: 14px;
    border-top: 1px solid #f1f1f1;
    input{
      text-indent: .5em;
      height: 22px;
      width: 350px;
      border: none;
    }
  }
  .should_pay{
    padding: 20px;
    overflow: hidden;
    border-top: 1px solid #f1f1f1;
  }
  .pay_type{
    padding: 20px;
    overflow: hidden;
    border-top: 1px solid #f1f1f1;
    input{
      display: none;
      &:checked + .pay{
        border-color: blue;
      }
    }
  }
  .coupon_type{//优惠券
    padding: 20px;
    overflow: hidden;
    border-top: 1px solid #f1f1f1;
    input {
      display: none;
    }
    /*
    input{
      display: none;
      &:checked + .coupon_detail{
        border-color: blue;
      }
    }*/
  }
  .coupon_detail{
    width: 320px;
    height: 93px;
    border: 5px solid #fff;
    font-weight: bold;
    float: left;
    line-height: 20px;
    text-align: center;
    background-repeat: no-repeat;
    background-position: center center;
    background-color: lightskyblue;
  }
  .study_card_type{//学习卡
    padding: 20px;
    overflow: hidden;
    border-top: 1px solid #f1f1f1;
    input{
      display: none;
      /*
      &:checked + .study_card_detail{
        border-color: blue;
      }*/
    }
  }
  .study_card_detail{
    width: 320px;
    height: 93px;
    border: 5px solid #fff;
    font-weight: bold;
    float: left;
    line-height: 20px;
    text-align: center;
    background-repeat: no-repeat;
    background-position: center center;
    background-color: lightblue;
  }
  .pay{
    width: 218px;
    height: 50px;
    border: 1px solid #fff;
    float: left;
    background-repeat: no-repeat;
    background-position: center center;
    &.pay_ali {
      background-image: url();
    }
    &.pay_weixin {
      background-image: url();
    }
  }
}
//paymodal强制显示滚动条开始-----
.modal_body::-webkit-scrollbar {
  width: 6px;
  height: 13px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}
.modal_body::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.5);
  background-clip: padding-box;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  min-height: 28px;
}
.modal_body::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.5);
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}
//paymodal强制显示滚动条结束-----
</style>
